package com.server.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class HttpRequest {
	private Socket socket;
	private InputStream in;
	//用于存储请求行
	private String line;
	//保存请求方式
	private String method;
	//用于保存完整请求
	private String uri;
	//用于保存	请求地址
	private String reqUri;
	//用于保存完整参数
	private Map<String, String> parameter = new HashMap<>();
	//用于保存请求头
	private Map<String, String> reqHeaders = new HashMap<>();
	
	public HttpRequest(Socket socket) throws EmptyRequestException {
		super();
		this.socket = socket;
		
		parseRequestLine();
		parseHeaders();
		parseContents();
	}
	
	
	//抛出空请求异常
	public void parseRequestLine() throws EmptyRequestException{

		String str = readLine();
		//判断是否为空请求
		if( "".equals(str) ){
			throw new EmptyRequestException();
		}
		String[] arr = str.split(" ");
		method = arr[0];
		uri = arr[1];
		parseUri();
		
	}
	
	
	
	public void parseHeaders(){
		String str = "";
		while(true){
			//判断是否为结尾
			if("".equals(str = readLine())){
				break;
			}
			String[] arr = str.split(": ");
			String key = arr[0];
			String value = arr[1];
			reqHeaders.put(key, value);
		}
	}
	
	
	
	
	
	public void parseContents(){
		System.out.println("解析请求正文");
		System.out.println("成功解析请求正文");
	}
	
	
	
	
	
	
	
	private String readLine(){
		StringBuilder str = new StringBuilder();
		try {
			in = socket.getInputStream();
			int pre = -1;
			int now = -1;
			while((now = in.read()) != -1){
				if(pre == 13 && now == 10){
					break;
				}
				pre = now;
				str.append((char) now);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str.toString().trim();

	}
	
	
	public void parseUri(){
//		System.out.println(uri.indexOf("?"));
		String[] uriArr = uri.split("\\?");
		reqUri = uriArr[0];
		String uriStr = "";
		if(uriArr.length > 1){
			try {
				uriStr = URLDecoder.decode(uriArr[1], "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String[] paraArr = uriStr.split("&");
			for(String paras : paraArr){
				String[] para = paras.split("=");
				parameter.put(para[0], para[1]);
			}
		}
			
	}
	
	
	
	public String getLine() {
		return line;
	}
	
	public String getMethod() {
		return method;
	}
	
	
	public String getReqUri() {
		return reqUri;
	}


	public String getParameter(String key) {
		return parameter.get(key);
	}


	public String getReqHeaders(String key) {
		return reqHeaders.get(key);
	}
	
	
}
